<template>
    <div>
        <el-dialog v-model="createStore.showCreateMember" title="客户信息表单" width="600px" center>
            <el-form ref="formRef" :model="formData" :rules="rules" label-width="130px" class="pr-10">
                <el-form-item label="客户姓名" prop="name">
                    <el-input v-model="formData.name" placeholder="请输入客户姓名" />
                </el-form-item>
                <el-form-item label="联系电话" prop="phone">
                    <el-input v-model="formData.phone" placeholder="请输入联系电话" />
                </el-form-item>
                <el-form-item label="客户地址" prop="address">
                    <el-input v-model="formData.address" placeholder="详细地址" style="width: 70%" />
                    <el-button type="primary" class="ml-2" :icon="Location" @click="openMap">定位位置</el-button>
                </el-form-item>
                <el-form-item label="客户类型" prop="type">
                    <el-select v-model="formData.type" placeholder="请选择客户类型">
                        <el-option label="包月" value="包月" />
                        <el-option label="季度" value="季度" />
                        <el-option label="年度" value="年度" />
                        <!-- 根据实际enum值添加更多选项 -->
                    </el-select>
                </el-form-item>
                <el-form-item label="所属分店" prop="shop">
                    <el-select v-model="formData.shop" placeholder="请选择所属分店">
                        <el-option 
                            v-for="shop in shopLists"
                            :key="shop.value"
                            :label="shop.label"
                            :value="shop.value"
                        />
                    </el-select>
                </el-form-item>

                <el-form-item label="会员标签" prop="tags">
                    <el-input v-model="formData.tags" placeholder="请输入标签;分隔" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="createStore.showCreateMember = false">取消</el-button>
                <el-button type="primary" @click="submitForm">提交</el-button>
            </template>
        </el-dialog>

        <!-- 地图组件 -->
        <el-dialog
            v-model="mapDialogVisible"
            title="选择服务地址"
            width="850px"
            :close-on-click-modal="false"
            class="map-dialog"
            draggable
        >
            <TMap 
                mode="createOrder" 
                @update:address="updateAddress"
                @close="closeMap" 
            />
        </el-dialog>
    </div>
</template>

<script setup lang="ts" name="createMember">
import { reactive, ref, watch } from 'vue';
import { useCreateStore } from '@/stores/useCreateStore';
import instance from '@/api';
import { ElMessage } from 'element-plus';
import { computed } from 'vue';
import { useStaffStore } from '@/stores/useStaffStore';
import { emitter } from '@/utils/emitter';
import { Location } from '@element-plus/icons-vue';
import TMap from '@/components/TMap.vue';

const staffStore = useStaffStore();
const createStore = useCreateStore();
const mapDialogVisible = ref(false);
const formRef = ref();

interface formDataType{
    name:string
    phone:string,
    address:string,
    type:string,
    shop:string,
    tags:string
}

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入客户姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  address: [
    { required: true, message: '请输入客户地址', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择客户类型', trigger: 'change' }
  ],
  shop: [
    { required: true, message: '请选择所属分店', trigger: 'change' }
  ]
}

// 表单数据对象
const formData = reactive<formDataType>({
  name: '',
  phone: '',
  address: '',
  type: '',
  shop: '',
  tags: ''
});

// 监听弹窗关闭事件
watch(() => createStore.showCreateMember, (newVal) => {
  if (!newVal) {
    // 清空表单数据
    Object.keys(formData).forEach(key => {
      formData[key as keyof formDataType] = '';
    });
    // 重置表单验证
    formRef.value?.resetFields();
  }
});

// 打开地图对话框
const openMap = () => {
  mapDialogVisible.value = true;
};

// 更新地址
const updateAddress = (address: string) => {
  formData.address = address;
};

// 关闭地图对话框
const closeMap = () => {
  mapDialogVisible.value = false;
};

// 表单提交方法
const submitForm = async () => {
  if (!formRef.value) return;
  
  // 表单验证
  await formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      console.log('提交表单数据', formData);
      const tagsArray = splitStringBySemicolon(formData.tags)
      const submitData = {
        ...formData,
        tags: tagsArray,
        contact_time: new Date().toISOString(),
        due_time: calculateExpireTime(formData.type)
      }
      const resp = await instance.post('/api/member/addMember', submitData)
      if(resp.status === 200) {
        ElMessage.success('添加成功')
        // 使用后端返回的完整数据
        emitter.emit('member-added', resp.data)
        createStore.showCreateMember = false;
      }
    } else {
      ElMessage.error('请填写完整的表单信息')
      return false;
    }
  });
};

// 计算到期时间
function calculateExpireTime(type: string): string {
  const now = new Date();
  switch(type) {
    case '包月':
      now.setMonth(now.getMonth() + 1);
      break;
    case '季度':
      now.setMonth(now.getMonth() + 3);
      break;
    case '年度':
      now.setFullYear(now.getFullYear() + 1);
      break;
    default:
      // 如果没有选择类型，默认返回当前时间
      return new Date().toISOString();
  }
  return now.toISOString();
}

function splitStringBySemicolon(input:string) {
  // 处理非字符串输入（可选）
  if (typeof input !== 'string') return [];
  
  // 按分号切割 -> 去除首尾空格 -> 过滤空字符串
  return input
    .split(';')
    .map(s => s.trim())
    .filter(s => s !== '');
}
const shopLists = computed(() => {
    return staffStore.shopList.map((shop: { id:number; shop_name: string }) => ({
        value: shop.id,
        label: shop.shop_name
    }))
})
</script>

<style scoped>
/* 可以根据需要微调表单样式 */
.el-form-item {
  margin-bottom: 15px;
}

:deep(.map-dialog .el-dialog) {
    margin-top: 5vh !important;
}

:deep(.map-dialog .el-dialog__body) {
    height: 520px;
    padding: 0;
    overflow: hidden;
}

:deep(.map-dialog .el-dialog__header) {
    padding: 0 10px;
    margin: 0;
}
</style>